package com.github.fancyideas.security.controller;

import com.github.fancyideas.security.module.entity.RoleEntity;
import com.github.fancyideas.security.module.entity.UserEntity;
import com.github.fancyideas.security.module.entity.UserRoleEntity;
import com.github.fancyideas.security.repository.RoleRepo;
import com.github.fancyideas.security.repository.UserRepo;
import com.github.fancyideas.security.repository.UserRoleRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/auth")
public class UserController {

    @Autowired
    private UserRepo userRepo;

    @Autowired
    private RoleRepo roleRepo;

    @Autowired
    private UserRoleRepo userRoleRepo;

    @PostMapping("/register")
    public UserEntity register(@RequestParam String username,
                               @RequestParam String password) {

        UserEntity entityUser = new UserEntity();
        entityUser.setUsername(username);
        entityUser.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
        entityUser = userRepo.save(entityUser);

        RoleEntity entityRole = new RoleEntity();
        entityRole.setRoleName("ROLE_ADMIN");
        entityRole = roleRepo.save(entityRole);

        UserRoleEntity entityUserRole = new UserRoleEntity();
        entityUserRole.setRoleId(entityRole.getRoleId());
        entityUserRole.setUserId(entityUser.getUserId());
        userRoleRepo.save(entityUserRole);

        return entityUser;
    }
}
